// pages/details/details.js
const app = getApp()
var wh = require("../../utils/wh.js");
var WxParse = require('../../wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [],
    apply_list: [],
    apply_lists: [],
    Registration: [],
    bargainImg: [],
    index: '1',
    allImg: '',
    isActive: true,
    modal: false,
    detail: '',
    page: 1,
    pages: 1,
    page_size: 5,
    activity_id: '',
    name: '',
    phone: '',
    footprint: '',
    ShopDetail: '',
    CollectHave: '',
    user_just:'',
    maskHidden: false, // 海报
    url: '',
    total:'',
    allImg:''
  },
  bindchange: function(e) {
    this.setData({
      index: e.detail.current + 1,
    })
  },
  applyList() {
    this.setData({
      isActive: false
    })
  },
  apply() {
    this.setData({
      modal: true
    })
  },
  applys() {
    wx.showToast({
      title: '您已报名参加了该活动',
      icon: 'none',
      image: '',
      duration:2000,
      mask: true,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  colse() {
    this.setData({
      modal: false
    })
  },
  // 上一页
  prePage: function () {
    let activity_id = this.data.activity_id
    let pages = this.data.pages;
    if (pages > 1) {
      this.data.page = pages - 1;
      this.enter_case(activity_id);
      this.setData({
        pages: pages - 1
      })
    }
  },
  // 下一页
  nextPage: function () {
    let activity_id = this.data.activity_id
    let pages = this.data.pages;
    let total = this.data.total;
    if (pages < total) {
      this.data.page = pages + 1;
      this.enter_case(activity_id);
      this.setData({
        pages: pages + 1
      })
    }
  },
  // 查看是否收藏
  CollectHave(activity_id) {
    var that = this;
    wh.Post('/api/mall.collect/have', {
      target_id: activity_id, 
      type: 2
    }, function(res) {
      console.log('是否收藏', res)
      that.setData({
        CollectHave: res
      })
    });
  },
  // 收藏提交
  CollectSubmit() {
    var that = this;
    wh.Post('/api/mall.collect/submit', {
      target_id: that.data.activity_id,
      type: 2
    }, function(res) {
      let CollectHave = !that.data.CollectHave;
      that.setData({
        CollectHave: CollectHave
      })
    })
  },
  // 获取商家店铺详情
  getShopDetail(shop_id) {
    var that = this;
    wh.Post('/api/mall.shop/detail', {
      shop_id: shop_id
    }, function(res) {
      console.log('店铺详情', res)
      that.setData({
        ShopDetail: res,
      })
    });
  },
  // 获取专题活动详情页面
  content(activityId) {
    let that = this;
    wh.Post('/api/mall.activity/content', {
      activity_id: activityId
    }, function(res) {
      WxParse.wxParse('activity_detail', 'html', res.activity_detail, that);
      that.getShopDetail(res.shop_id)
      console.log('详情', res)
      that.getFootList(res.shop_id, activityId)
      // that.FootMarkRecord(res.shop_id, activityId)
      that.setData({
        detail: res,
        activity_id: res.activity_id
      })
    });
  },
  // 获取活动报名情况
  enter_case(activityId) {
    let that = this,
      page = this.data.page,
      page_num = this.data.page_size;
    wh.Post('/api/mall.activity/enter_case', {
      activity_id: activityId,
      page: page,
      page_num: page_num
    }, function(res) {
      let num = parseInt(res.total) / parseInt(that.data.page_size);
      let p1 = num.toFixed(1);
      let p2 = parseInt(num);
      let total = p2;
      if ((p1 - p2) > 0) {
        total = p2 + 1;
      }
      console.log('报名', res)
      that.setData({
        apply_list: res.list,
        total: total
      })
    });
  },
  // 获取活动报名总人数
  enter_cases(activityId) {
    let that = this;
    wh.Post('/api/mall.activity/enter_case', {
      activity_id: activityId,
      page: 1,
      page_num: 10
    }, function(res) {
      that.setData({
        apply_lists: res.list,
      })
    });
  },
  // 获取推荐活动
  special() {
    let that = this;
    wh.Post('/api/mall.activity/lists', {
      is_recom: 1
    }, function(res) {
      console.log('推荐', res)
      that.setData({
        Registration: res
      })
    });
  },
  // 立即预约
  bindName: function(e) {
    this.setData({
      name: e.detail.value
    })
  },
  bindPhone: function(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  formSubmit: function(e) {
    console.log(e.detail)
    let name = this.data.name,
      phone = this.data.phone,
      activity_id = this.data.activity_id;
    if (!name || !phone) {
      wx.showToast({
        title: '请填写完整信息',
        icon: "none"
      })
      return false;
    }
    if (!(/^1[34578]\d{9}$/.test(phone))) {
      wx.showToast({
        title: '手机号格式错误',
        icon: "none"
      })
      return false;
    }
    wh.Post('/api/mall.activity/enter', {
      activity_id: activity_id,
      name: name,
      mobile: phone,
      form_id: e.detail.formId,
    }, function(res) {
      console.log(res)
      // 微信支付
      wx.requestPayment({
        'timeStamp': res.timeStamp + '',
        'nonceStr': res.nonceStr,
        'package': res.package,
        'signType': res.signType,
        'paySign': res.paySign,
        'success': function (ref) {
          console.log('支付成功', ref)
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 2000,
            complete: function () {
              wx.showToast({
                title: '报名成功',
                complete: function () {
                  setTimeout(function () {
                    wx.navigateTo({
                      url: '..person/userjoin'
                    })
                  }, 2000);
                }
              })
            }
          })
        },
      })
    });
  },
  // 获取用户足迹展示列表
  getFootList(shop_id, activity_id) {
    let that = this;
    wh.Post('/api/mall.footmark/lists', {
      shop_id: shop_id,
      target_id: activity_id,
      type: 2
    }, function(res) {
      console.log('足迹', res)
      that.setData({
        footprint: res
      })
    });
  },
  // 记录用户访问足迹
  FootMarkRecord(shop_id, activity_id) {
    wh.Post('/api/mall.footmark/record', {
      shop_id: shop_id,
      target_id: activity_id,
      type: 2
    }, function(res) {

    })
  },
  // 打电话
  call: function () {
    let that = this;
    let tell = that.data.ShopDetail.tell;

    if (tell == '' || tell == undefined) {

      wx.showModal({
        title: '提示',
        content: '联系电话未设置，不能联系',
        showCancel: false
      })
      return;
    }
    wx.makePhoneCall({
      phoneNumber: tell,
    })
  },
  // 导航
  go: function () {
    var that = this;
    let setting = that.data.ShopDetail;
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度  
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var latitudeIdx = Number(setting.latitude);
        var longitudeIdx = Number(setting.longitude);
        var map_name = setting.shop_name;
        wx.openLocation({
          latitude: latitudeIdx,
          longitude: longitudeIdx,
          name: map_name,
          scale: 15
        })
      }
    })
  },
  // 某某某刚刚参与了活动
  user_just(activity_id){
    let that=this;
    wh.Post('/api/mall.activity/just', {
      activity_id: activity_id
    }, function (res) {
      console.log('某某某刚刚参与了活动',res)
      that.setData({
        user_just:res
      })
    })
  },
  // 获取url
  url() {
    let that = this;
    wx.getExtConfig({
      success: function (res) {
        console.log(2, res)
        let url = res.extConfig.apiurl;
        that.setData({
          url: url
        })
      }
    })
  },
  /** 
 * 生成海报
 */
  createPoster: function () {
    let param = this.data.detail,
      url = this.data.url,
      that = this,
      postUrl = '/api/mall.ajax/page_qrcode',
      tag = '活动',
      s_url = 'pages/events/events?activityId=' + this.data.detail.activity_id;
    setTimeout(() => {
      wx.showToast({
        title: '海报生成中...',
        icon: "loading",
      });
      setTimeout(() => {
        wx.hideToast();
      }, 10000)
    }, 0);
    param.title = param.title;
    param.goods_desc = param.activity_desc;
    param.price = param.activity_price;
    param.market_price = param.activity_price;
    // 获取小程序码
    wh.Post(postUrl, { s_url: s_url }, function (imgUrl) {
      console.log(imgUrl)
      // 将图片保存到本地
      wx.getImageInfo({
        src: param.cover,   //请求的网络图片路径
        success: function (res1) {
          param.path1 = res1.path;
          wx.getImageInfo({
            src: imgUrl,    //请求的网络图片路径
            success: function (res2) {
              param.path2 = res2.path;
              // 开始绘制
              app.startToDraw(param, url, tag, imgUrl);
              that.setData({
                maskHidden: true
              });
              // 将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
              setTimeout(function () {
                // wx.hideLoading()
                wx.canvasToTempFilePath({
                  canvasId: 'mycanvas',
                  success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    that.setData({
                      imagePath: tempFilePath,
                      canvasHidden: true
                    });
                  },
                  fail: function (res) {
                    console.log(res);
                  }
                });
              }, 200);
            }
          });
        }
      });
    });
  },
  /**
   * 点击保存到相册
   */
  poster_save: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        that.setData({
          maskHidden: false
        });
        wx.showToast({
          title: '图片已保存到相册',
        });
      }
    })
  },
  /**
   * 关闭海报
   */
  close_share: function () {
    this.setData({
      maskHidden: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options.activityId)
    this.content(options.activityId)
    this.enter_case(options.activityId)
    this.enter_cases(options.activityId)
    this.CollectHave(options.activityId)
    this.user_just(options.activityId)
    this.special()
    let allNum = this.data.imgUrls.length
    this.setData({
      allImg: allNum,
      activityId: options.activityId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})